<template>
  <div class="course-platform">
    <el-row>
      <el-col :span="6">
        <div class="sidebar">
          <h3>个人信息</h3>
          <el-card>
            <div class="user-info">
              <router-link
                  v-if="userInfo && userInfo.stu_name"
                  :to="{ name: 'ProfilePage',  query: {profileuser_id:userInfo.stu_id, user_id: userInfo.stu_id} }"
              >
                <el-avatar style="cursor: pointer">
                  {{ userInfo.stu_name.charAt(0) }}
                </el-avatar>
              </router-link>
              <p v-if="userInfo.stu_name">{{ userInfo.stu_name }}</p>
              <p v-if="userInfo.stu_class">班级：{{ userInfo.stu_class }}</p>
              <p v-if="userInfo.stu_email">邮箱：{{ userInfo.stu_email }}</p>
              <p v-if="isEditing">
                <el-input v-model="editableUserInfo.stu_email" placeholder="邮箱"/>
              </p>
              <p v-if="isEditing">
                <el-input v-model="editableUserInfo.stu_class" placeholder="班级"/>
              </p>
              <el-button type="primary" @click="showChangePasswordDialog">修改密码</el-button>
            </div>
          </el-card>
          <el-card class="ai-area">
            <div class="ai-section">
              <el-button type="success" @click="goToAIPage">AI 智能助手</el-button>
            </div>
          </el-card>
        </div>
      </el-col>

      <el-col :span="12">
        <div class="main-content">
          <h2>课程列表</h2>
          <el-row :gutter="20">
            <el-col :span="8" v-for="course in courses" :key="course.course_id" @click="goToCourseDetail(course)">
              <el-card>
                <div class="course-info">
                  <el-image :src="courseImage" fit="contain"/>
                  <div class="course-details">
                    <h4>{{ course.course_name }}</h4>
                    <p>课程号：{{ course.course_id }}</p>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>
      </el-col>

      <el-col :span="6">
        <div class="notification">
          <div class="notification-header">
            <h3>通知公告</h3>
            <el-button type="primary" @click="goToNoticePage" class="view-button">查看通知</el-button>
          </div>
        </div>
        <div class="calendar">
          <h3>时间列表</h3>
          <el-calendar v-model="currentDate"/>
        </div>
      </el-col>
    </el-row>

    <!-- 修改密码对话框 -->
    <div v-if="changePasswordDialogVisible" class="custom-dialog-overlay" @click.self="closeChangePasswordDialog">
      <div class="custom-dialog">
        <h2>修改密码</h2>

        <!-- 输入新密码 -->
        <el-input
            v-model="newPassword"
            type="password"
            placeholder="输入新密码"
        ></el-input>

        <!-- 确认新密码 -->
        <el-input
            v-model="confirmPassword"
            type="password"
            placeholder="确认新密码"
            style="margin-top: 10px"
        ></el-input>

        <!-- 错误提示 -->
        <span class="error-text">{{ passwordError }}</span>

        <div class="dialog-footer">
          <el-button @click="closeChangePasswordDialog">取消</el-button>
          <el-button type="primary" @click="saveNewPassword">确定</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {ref, onMounted} from 'vue';
import axios from 'axios';
import {useRouter} from 'vue-router';
import {BASE_URL} from '@/config';
import courseImage from '@/assets/course.png';

export default {
  setup() {
    const selectedTerm = ref('');
    const router = useRouter();
    const userInfo = ref({});
    const editableUserInfo = ref({stu_email: '', stu_class: ''});
    const courses = ref([]);
    const currentDate = ref(new Date());
    const isEditing = ref(false);
    const changePasswordDialogVisible = ref(false);
    const newPassword = ref('');
    const passwordError = ref('');
    const notifications = ref({unreadSchool: 0, unreadCourse: 0});
    const username = router.currentRoute.value.query.username;
    const confirmPassword = ref('');

    const saveNewPassword = async () => {
      // 验证两次密码是否一致
      if (newPassword.value !== confirmPassword.value) {
        passwordError.value = '两次输入的密码不一致';
        return;
      }

      // 验证密码长度
      if (newPassword.value.length < 6) {
        passwordError.value = '密码至少6位字符';
        return;
      }

      try {
        const response = await axios.put(`${BASE_URL}/student/update`, {
          stu_id: username,
          stu_password: newPassword.value,
        });
        if (response.status === 200) {
          closeChangePasswordDialog();
          alert("密码修改成功！");
        }
      } catch (error) {
        console.error('修改密码失败:', error);
        alert("修改密码失败，请重试！");
      }
    };

    const fetchUserInfo = async () => {
      try {
        const response = await axios.post(`${BASE_URL}/student/showStudentMsg`, {stu_id: username});
        userInfo.value = response.data.data || {};
        editableUserInfo.value.stu_email = userInfo.value.stu_email || '';
      } catch (error) {
        console.error('获取用户信息失败:', error);
      }
    };

    const fetchCourses = async () => {
      try {
        const response = await axios.post(`${BASE_URL}/student/stuCourse`, {stu_id: username});
        courses.value = response.data.data || [];
      } catch (error) {
        console.error('获取课程列表失败:', error);
      }
    };

    const goToCourseDetail = (course) => {
      router.push({name: 'courseDetail', params: {course_id: course.course_id}});
    };

    const showChangePasswordDialog = () => {
      changePasswordDialogVisible.value = true;
      newPassword.value = '';
      passwordError.value = '';
    };

    const closeChangePasswordDialog = () => {
      changePasswordDialogVisible.value = false;
    };

    const goToNoticePage = () => {
      router.push({name: 'NoticePage'});
    };

    const goToAIPage = () => { // 跳转到AI页面
      router.push({ name: 'AIDialogue' });
    };


    onMounted(() => {
      fetchUserInfo();
      fetchCourses();
    });

    return {
      courseImage, selectedTerm, userInfo, editableUserInfo, courses,
      currentDate, goToCourseDetail, isEditing, showChangePasswordDialog,  confirmPassword,
      closeChangePasswordDialog, changePasswordDialogVisible, newPassword, saveNewPassword, passwordError,
      goToNoticePage, goToAIPage
    };
  },
};
</script>

<style scoped>
.course-platform {
  padding: 20px;
}

.sidebar {
  background-color: #f2f7fc;
  padding: 20px;
}

.main-content {
  background-color: #ffffff;
  padding: 20px;
}

.notification {
  background-color: #f2f7fc;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

/* 使用 Flexbox 对齐标题和按钮 */
.notification-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.notification h3 {
  margin: 0;
  font-size: 20px;
}

.view-button {
  margin-left: 10px;
}

.calendar {
  margin-top: 20px;
}

.custom-dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.custom-dialog {
  background: white;
  padding: 20px;
  width: 400px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.error-text {
  color: red;
  font-size: 14px;
}

.ai-area {
  margin-top: 20px;
  background-color: #e6f7ff;
  padding: 15px;
  border-radius: 8px;
  text-align: center;
}

.ai-section {
  display: flex;
  justify-content: center;
  align-items: center;
}

</style>
